package com.sf.audit.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.sf.appointment.domain.BusServiceItem;
import com.sf.appointment.mapper.BusServiceItemMapper;
import com.sf.audit.vo.AuditInfoHistory;
import com.sf.audit.vo.AuditVo;
import com.sf.common.utils.DateUtils;
import com.sf.common.utils.PageUtils;
import com.sf.common.utils.SecurityUtils;
import com.sf.management.domain.BusBpmnInfo;
import com.sf.management.mapper.BusBpmnInfoMapper;
import io.jsonwebtoken.lang.Assert;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.*;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.sf.audit.mapper.BusCarPackageAuditMapper;
import com.sf.audit.domain.BusCarPackageAudit;
import com.sf.audit.service.IBusCarPackageAuditService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

/**
 * 套餐审核Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-30
 */
@Service
@Transactional
public class BusCarPackageAuditServiceImpl implements IBusCarPackageAuditService 
{
    @Autowired
    private BusCarPackageAuditMapper busCarPackageAuditMapper;


    @Autowired
    private BusBpmnInfoMapper busBpmnInfoMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private BusServiceItemMapper busServiceItemMapper;

    @Autowired
    private HistoryService historyService;
    @Qualifier("variableTypeMap")
    @Autowired
    private Map variableTypeMap;

    /**
     * 查询套餐审核
     * 
     * @param id 套餐审核主键
     * @return 套餐审核
     */
    @Override
    public BusCarPackageAudit selectBusCarPackageAuditById(Long id)
    {
        return busCarPackageAuditMapper.selectBusCarPackageAuditById(id);
    }

    /**
     * 查询套餐审核列表
     * 
     * @param busCarPackageAudit 套餐审核
     * @return 套餐审核
     */
    @Override
    public List<BusCarPackageAudit> selectBusCarPackageAuditList(BusCarPackageAudit busCarPackageAudit)
    {
        Long userId = SecurityUtils.getUserId();
        busCarPackageAudit.setCreatorId(userId.toString());
        return busCarPackageAuditMapper.selectBusCarPackageAuditList(busCarPackageAudit);
    }

    /**
     * 新增套餐审核
     * 
     * @param busCarPackageAudit 套餐审核
     * @return 结果
     */
    @Override
    public int insertBusCarPackageAudit(BusCarPackageAudit busCarPackageAudit)
    {
        busCarPackageAudit.setCreateTime(DateUtils.getNowDate());
        return busCarPackageAuditMapper.insertBusCarPackageAudit(busCarPackageAudit);
    }

    /**
     * 修改套餐审核
     * 
     * @param busCarPackageAudit 套餐审核
     * @return 结果
     */
    @Override
    public int updateBusCarPackageAudit(BusCarPackageAudit busCarPackageAudit)
    {
        return busCarPackageAuditMapper.updateBusCarPackageAudit(busCarPackageAudit);
    }

    /**
     * 批量删除套餐审核
     * 
     * @param ids 需要删除的套餐审核主键
     * @return 结果
     */
    @Override
    public int deleteBusCarPackageAuditByIds(Long[] ids)
    {
        return busCarPackageAuditMapper.deleteBusCarPackageAuditByIds(ids);
    }

    /**
     * 删除套餐审核信息
     * 
     * @param id 套餐审核主键
     * @return 结果
     */
    @Override
    public int deleteBusCarPackageAuditById(Long id)
    {
        return busCarPackageAuditMapper.deleteBusCarPackageAuditById(id);
    }

    @Override
    public int process(Long id, HttpServletResponse response) throws IOException {

        BusCarPackageAudit busCarPackageAudit = busCarPackageAuditMapper.selectBusCarPackageAuditById(id);
        if (busCarPackageAudit == null){
            throw new RuntimeException("id不合法");
        }
        BusBpmnInfo bpmnInfo=new BusBpmnInfo();
        bpmnInfo.setBpmnType(0);
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoByTypeOnlyOne(bpmnInfo);
        if (busBpmnInfo == null){
            throw  new RuntimeException("操作错误");
        }
        List<String> activeActivityIds;
        if(BusCarPackageAudit.STATUS_IN_ROGRESS.equals(busCarPackageAudit.getStatus())){
            activeActivityIds = runtimeService.getActiveActivityIds(busCarPackageAudit.getInstanceId());
        }else{
            activeActivityIds=null;
        }

        // 如果 activeActivityIds 为空，则以无高亮状态展示流程图
        if (activeActivityIds == null || activeActivityIds.isEmpty()) {
            activeActivityIds = Collections.emptyList();
        }
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(busBpmnInfo.getProcessDefinitionKey()).processDefinitionVersion(busBpmnInfo.getVersion().intValue()).singleResult();
        DefaultProcessDiagramGenerator processDiagramGenerator=new DefaultProcessDiagramGenerator();
        BpmnModel bpmnModel=repositoryService.getBpmnModel(processDefinition.getId());
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel,
                activeActivityIds,
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体");
        return IOUtils.copy(inputStream,response.getOutputStream());
    }

    @Override
    public void cancel(Long id) {
        BusCarPackageAudit busCarPackageAudit = busCarPackageAuditMapper.selectBusCarPackageAuditById(id);
        if (busCarPackageAudit == null){
            throw new RuntimeException("操作错误");
        }
        if (BusCarPackageAudit.STATUS_IN_ROGRESS.equals(busCarPackageAudit.getStatus())){
            busCarPackageAudit.setStatus(BusCarPackageAudit.STATUS_CANCEL);
            busCarPackageAuditMapper.updateBusCarPackageAudit(busCarPackageAudit);
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(busCarPackageAudit.getServiceItemId());
        if (busServiceItem==null){
            throw new RuntimeException("操作不合法");
        }
        if(BusServiceItem.AUDITSTATUS_AUDITING.equals(busServiceItem.getAuditStatus())){
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
            busServiceItemMapper.updateBusServiceItem(busServiceItem);
        }
        String instanceId = busCarPackageAudit.getInstanceId();
        runtimeService.deleteProcessInstance(instanceId,"已撤销");
    }

    @Override
    public List<BusCarPackageAudit> todolist() {
        BusBpmnInfo bpmnInfo=new BusBpmnInfo();
        bpmnInfo.setBpmnType(0);
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoByTypeOnlyOne(bpmnInfo);
        String processDefinitionKey = busBpmnInfo.getProcessDefinitionKey();
        Long userId = SecurityUtils.getUserId();
        List<Task> list = taskService.createTaskQuery().taskAssignee(userId.toString()).processDefinitionKey(processDefinitionKey).list();
        List<Long> list1=new ArrayList<>();
        for (Task task : list) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            Long id=new Long(businessKey);
            list1.add(id);
        }
        PageUtils.startPage();
        List<BusCarPackageAudit> busCarPackageAudits = busCarPackageAuditMapper.selectBusCarPackageBybusinessKey(list1);
        return busCarPackageAudits;
    }

    @Override
    public void audit(AuditVo auditVo) {
        Assert.notNull(auditVo.getAuditStatus(),"审批结果不能为空");
        Assert.notNull(auditVo.getId(),"id不能为空");
        Assert.notNull(auditVo.getInfo(),"备注不能为空");

        BusCarPackageAudit busCarPackageAudit = busCarPackageAuditMapper.selectBusCarPackageAuditById(auditVo.getId());
        if (busCarPackageAudit == null){
            throw new RuntimeException("id不合法");
        }
        if (BusCarPackageAudit.STATUS_IN_ROGRESS.equals(busCarPackageAudit.getStatus())){
            String instanceId = busCarPackageAudit.getInstanceId();
            Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
            String auditStatus = auditVo.getAuditStatus();
            Boolean flag;
            if (auditStatus.equals("true")){
                flag=true;
            }else{
                flag=false;
            }
            Map<String,Object> map=new HashMap<>();
            map.put("shopOwner",flag);
            String msg;
            if (flag){
                msg="审批人:"+SecurityUtils.getLoginUser().getUsername()+" 审批通过,审批意见为:"+auditVo.getInfo();
            }else{
                msg="审批人:"+SecurityUtils.getLoginUser().getUsername()+" 审批失败,审批意见为:"+auditVo.getInfo();
            }
            taskService.addComment(task.getId(),task.getProcessInstanceId(),msg);
            taskService.complete(task.getId(),map);
            if (flag){
                Task task1 = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
                if (task1 == null){
                busCarPackageAudit.setStatus(BusCarPackageAudit.STATUS_PASS);
                busCarPackageAuditMapper.updateBusCarPackageAudit(busCarPackageAudit);
                BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(busCarPackageAudit.getServiceItemId());
                if (busServiceItem == null){
                    throw new RuntimeException("操作失败");
                }
                busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_APPROVED);
                busServiceItemMapper.updateBusServiceItem(busServiceItem);
                }
            }else {
                busCarPackageAudit.setStatus(BusCarPackageAudit.STATUS_REJECT);
                busCarPackageAuditMapper.updateBusCarPackageAudit(busCarPackageAudit);
                BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(busCarPackageAudit.getServiceItemId());
                if (busServiceItem == null){
                    throw new RuntimeException("操作失败");
                }
                busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_REPLY);
                busServiceItemMapper.updateBusServiceItem(busServiceItem);
            }
        }else{
            throw new RuntimeException("状态不合法");
        }
    }

    @Override
    public List<AuditInfoHistory> history(Long instanceId) {
        Assert.notNull(instanceId,"查询id不能为空");
        List<AuditInfoHistory> au=new ArrayList<>();
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(instanceId.toString()).list();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (HistoricActivityInstance historicActivityInstance : list) {
            String taskId = historicActivityInstance.getTaskId();
            if (taskId!=null){
                AuditInfoHistory auditInfoHistory = new AuditInfoHistory();
                String activityName= historicActivityInstance.getActivityName();
                String startTime = sdf.format(historicActivityInstance.getStartTime());
                String endTime = sdf.format(historicActivityInstance.getEndTime());
                auditInfoHistory.setTaskName(activityName);
                auditInfoHistory.setStartTime(startTime);
                auditInfoHistory.setEndTime(endTime);
                auditInfoHistory.setDurationInMillis(historicActivityInstance.getDurationInMillis()/1000+"s");
                List<Comment> comments = taskService.getTaskComments(taskId);
                if(comments.size()>0){
                    auditInfoHistory.setComment(comments.get(0).getFullMessage());
                }
                au.add(auditInfoHistory);
            }
        }


        return au;
    }

    @Override
    public List<BusCarPackageAudit> donelist() {
        BusBpmnInfo bpmnInfo=new BusBpmnInfo();
        bpmnInfo.setBpmnType(0);
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoByTypeOnlyOne(bpmnInfo);
        String processDefinitionKey = busBpmnInfo.getProcessDefinitionKey();
        Long userId = SecurityUtils.getUserId();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processDefinitionKey(processDefinitionKey).taskAssignee(userId.toString()).list();
        List<Long> businessIds = new ArrayList<>();
        for (HistoricTaskInstance historicTaskInstance : list) {
            String processInstanceId = historicTaskInstance.getProcessInstanceId();
            List<HistoricProcessInstance> list1 = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).list();
            for (HistoricProcessInstance historicProcessInstance : list1) {
                Date endTime = historicProcessInstance.getEndTime();
                if (endTime!=null){
                    Long businessKey=new Long(historicProcessInstance.getBusinessKey());
                    businessIds.add(businessKey);
                }

            }
        }
        PageUtils.startPage();
        List<BusCarPackageAudit> busCarPackageAudits = busCarPackageAuditMapper.selectBusCarPackageBybusinessKey(businessIds);

        return  busCarPackageAudits;
    }
}
